package com.spring.sample.conf;

import java.util.Properties;

import javax.annotation.Resource;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springmodules.commons.configuration.CommonsConfigurationFactoryBean;


@Configuration
public class SpringPropertyFileConf {
	
	final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource Properties conf;
	@Resource CompositeConfiguration compositeConfiguration;
	
	@Bean
	public PropertyPlaceholderConfigurer springPlaceholders(){
		PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
		propertyPlaceholderConfigurer.setProperties(conf);
		return propertyPlaceholderConfigurer;
	}
	
	@Bean
	public CommonsConfigurationFactoryBean conf(){
		CommonsConfigurationFactoryBean commonsConfigurationFactoryBean = new CommonsConfigurationFactoryBean();
		commonsConfigurationFactoryBean.setConfigurations(new CompositeConfiguration[]{compositeConfiguration});
		return commonsConfigurationFactoryBean;
		
	}
	
	@Bean
	public CompositeConfiguration compositeConfiguration(){
		CompositeConfiguration compositeConfiguration = new CompositeConfiguration(getXmlConfiguration());
		return compositeConfiguration;
		
	}

	private XMLConfiguration getXmlConfiguration(){
		XMLConfiguration xmlConfiguration=null;
		try {
			ClassLoader classLoader = this.getClass().getClassLoader();
			/*	경로를 찾을때 제일 앞에 '/'는 빼고 해야 한다...	 */
			xmlConfiguration = new XMLConfiguration(classLoader.getResource("properties/"+System.getProperty("operation.mode")+"/im.xml"));
		} catch (ConfigurationException e) {
			e.printStackTrace();
			throw new RuntimeException("property xml 파일 읽기 오류!");
		}
		xmlConfiguration.setReloadingStrategy(getReloadStrategy());
		return xmlConfiguration;
	}
	
	private FileChangedReloadingStrategy getReloadStrategy() {
		FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
		strategy.setRefreshDelay(2000);
		return strategy;
	}

}
